import React, { Component, PropTypes } from 'react';
import { Select } from 'antd';
import { ReportParamSearch } from '../../services/report';

const Option = Select.Option;

const SearchInput2 = React.createClass({
    getInitialState() {
        const val = this.props.initValue
        return {
            data: [],
            value: val,
        };
    },
    componentDidMount() {
        this.fetch()
    },
    handleSelect(value, option) {
        this.props.onChange(value);
        if (this.props.onSelect) {
            const sData = this.getSelectData(value)
            this.props.onSelect(sData)
        }
        this.setState({ value: option.props.children });
    },
    getSelectData(value) {
        const data = this.state.data;
        let selectData = null;
        Object.keys(data).map(key => {
            if (key === value) {
                selectData = { label: data[key], value: key }
            }
        })
        return selectData;
    },
    fetch(searchValue) {
        if (!searchValue) {
            searchValue = this.state.value
        }
        if (searchValue !== '') {
            let params = this.props.params
            params = { ...params, searchValue }
            ReportParamSearch(params
            ).then(function (data) {
                this.setState({ data, value: searchValue });
            }.bind(this)).catch(function (ex) {
                console.log('请求出错', ex)
            });
        }
    },
    handleChange(value) {
        if (value && value.replace(/(^\s*)|(\s*$)/g, '') !== '') {
            this.fetch(value)
        }
    },
    render() {
        const { placeholder } = this.props;
        const { data, value } = this.state;
        const options = Object.keys(data).map(id => <Option key={id} value={'' + id}>{data[id]}</Option>);
        return (
            <Select
                combobox
                value={value}
                placeholder={this.props.placeholder}
                defaultActiveFirstOption={false}
                showArrow={false}
                filterOption={false}
                onSearch={this.handleChange}
                onSelect={this.handleSelect}
            >
                {options}
            </Select>
        );
    },
});

SearchInput2.propTypes = {
    initValue: PropTypes.string,
    placeholder: PropTypes.string,
    params: PropTypes.object,
    onSelect: PropTypes.func
};
SearchInput2.defaultProps = {
    placeholder: "请输入...",
    initValue: ""
};
export default SearchInput2;